package imgtagcounter;

import java.io.*;
import java.util.ArrayList;

/**
 * parsing user's input to enable easy access
 * @author Oleg Ruchlis & Marcelo Korn
 */
public class UserInputReader implements UrlListInterface{
    
    /**
     * List of all URLs
     */ 
    protected ArrayList urlList = new ArrayList();
    
    /**
     * Keeps track of the current position in the urlList.
     */ 
    protected int index = 0;

    /**
     * Class builder, receives the path of the input file.
     * @param path The full path of the input file.
     * @throws IOException When fails in opening the input file
     */
    UserInputReader(String path) throws IOException {
        FileInputStream fstream = null;
        
        try {
            fstream = new FileInputStream(path);
        } catch (FileNotFoundException ex) {
            throw new IOException("Couldn't open the path: " + path + "\r\n" +
                                  "Reason: " + ex.getMessage());
        }
        
        // enabling readLine() through buffered reader.
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine = null;
        
        // putting the urls in the list.
        while((strLine = br.readLine()) != null){
            // trimming white spaces
            strLine.trim();
            // making sure URL is valid
            if(checkUrl(strLine))
                urlList.add(strLine);
            else
                System.out.println("The following url is incorrect: " + 
                                    strLine + "\r\nPlease make sure that " +
                                   "the address contains http://...");
        }
        try{
            br.close();
            in.close();
            fstream.close();
        }
        catch(Exception ex){
            // if a close fails, there is nothing we can do.
        }
    }
    
    /**
     * Provides the next URL.
     * @return String that is the next URL from user's input.
     */
    @Override
    public String getNextElement(){
        // making sure we are within the legal range.
        if(index >= urlList.size())
            return null;
        return((String)urlList.get(index++));
    }
    /**
     * Let's the user know the total size of user's (valid) input.
     * @return int, the number of entries in the urlList.
     */
    @Override
    public int getListSize(){
        return(urlList.size());
    }

    /**
     * Making sure the URL received is valid
     * @param line contains the URL received from user (one input line).
     * @return true - The URL seems fine. <br>
     * false - Problem with URL.
     */
    private boolean checkUrl(String line) {
        if(!line.startsWith("http://"))
            return(false);
        return(true);
    }
}
